package com.sky.moduels.mini.event;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sky.common.Utils.IDUtils;
import com.sky.moduels.mini.repository.enums.UserStatus;
import com.sky.moduels.mini.repository.model.UserDO;
import com.sky.moduels.mini.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @Description: 事件消息异步处理
 * @ClassName: EventMessageService
 * @Author: hupengming
 * @CreateTime: 2022-08-22 10:29
 */
@Slf4j
@Service
public class EventMessageService {

    @Autowired
    UserService userService;

    /**
     * 关注事件
     *
     * @param subscribeEvent
     */
    @Async
    @EventListener(SubscribeEvent.class)
    public void subscribe(SubscribeEvent subscribeEvent) {
        log.info("关注事件触发...{}", subscribeEvent.getOpenId());
        log.info("thread:{}",Thread.currentThread().getId());
        String openId = subscribeEvent.getOpenId();
        UserDO userByOpenId = userService.getUserByOpenId(openId);
        if (ObjectUtils.isNull(userByOpenId)) {
            userByOpenId = new UserDO();
            userByOpenId.setOpenId(openId);
            userByOpenId.setStatus(UserStatus.ENABLE);
            userByOpenId.setCreatedAt(new Date());
            userByOpenId.setUuid(IDUtils.UUID());
            userService.createdUser(userByOpenId);
            return;
        }

        userByOpenId.setStatus(UserStatus.ENABLE);
        userByOpenId.setUpdatedAt(new Date());

        userService.updateUser(userByOpenId);
    }

    /**
     * 取消关注事件
     *
     * @param unSubscribeEvent
     */
    @Async
    @EventListener(UnSubscribeEvent.class)
    public void unSubscribe(UnSubscribeEvent unSubscribeEvent) {
        log.info("取消关注事件触发...{}", unSubscribeEvent.getOpenId());
        log.info("thread:{}",Thread.currentThread().getId());
        String openId = unSubscribeEvent.getOpenId();
        UserDO userByOpenId = userService.getUserByOpenId(openId);
        if(ObjectUtils.isNotNull(userByOpenId)){
            userByOpenId.setStatus(UserStatus.DISABLE);
            userByOpenId.setUpdatedAt(new Date());
            userService.updateUser(userByOpenId);
        }
    }


}
